#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

int DHpin = 7;
byte dat[5];
byte read_data(){
  byte data;
  for(int i=0; i<8; i++){
    if(digitalRead(DHpin)==LOW){
      while(digitalRead(DHpin)==LOW);
      delayMicroseconds(30);
      if(digitalRead(DHpin)==HIGH){
          data |= (1<<(7-i));
      }  
      while(digitalRead(DHpin)==HIGH);
    }
  }
  return data;
}

void start_test()
{
  digitalWrite(DHpin, LOW);
  digitalWrite(DHpin, HIGH);
  delayMicroseconds(40);
  pinMode(DHpin, INPUT);
  while(digitalRead(DHpin)==HIGH);
  delayMicroseconds(80);
  if(digitalRead(DHpin)==LOW);
  delayMicroseconds(80);
  for(int i=0; i<4; i++){
    dat[i] = read_data();
  }  
  pinMode(DHpin, OUTPUT);
  digitalWrite(DHpin, HIGH);
}

void setup() {
  // put your setup code here, to run once:
//  lcd.init();
//  lcd.backlight();
//  lcd.print("hello master");
//  lcd.setCursor(0, 1);
//  lcd.print("Zhang Martin");
  Serial.begin(9600);
  pinMode(DHpin, OUTPUT);
  lcd.init();
  lcd.backlight();
}

void loop() {
  // put your main code here, to run repeatedly:
  start_test();
  lcd.setCursor(0, 0);
  lcd.print("Hu: ");
  lcd.print(dat[0], DEC);
  lcd.print('.');
  int temp = 0;
  if (dat[1]<10){
    temp = dat[1];
  }else if(dat[1]>10 && dat[1]<100){
    temp = dat[1] / 10;  
  }else if(dat[1] > 100){
    temp = dat[1] / 100;
  }
  lcd.print(temp, DEC);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print("Te: ");
  lcd.print(dat[2], DEC);
  lcd.print('.');
  int temp2 = 0;
  if (dat[3]<10){
    temp2 = dat[3];
  }else if(dat[3]>10 && dat[3]<100){
    temp2 = dat[3] / 10;  
  }else if(dat[3] > 100){
    temp2 = dat[3] / 100;
  }
  lcd.print(temp2, DEC);
  lcd.print("C");
  delay(1000);
}